// smoke 烟雾报警监听接口
#include <stdio.h>
#include "control.h"
#include "msg_queue.h"
#include "global.h"
#include "wiringPi.h"
#include <pthread.h>
#include "smoke_interface.h"
#include <unistd.h>

static int somke_init(void)
{
    // 配置输入模式
    pinMode(SOMKE_PIN, SMOKE_MODE);

    return 0;
}

static void somke_final(void)
{
}

static void *somke_get(void *arg)
{
    int status = HIGH;
    int switch_status = 0;
    mqd_t mqd = -1;
    unsigned char buffer[6] = {0xAA, 0x55, 0x00, 0x00, 0x55, 0xAA};
    ctr_info_t *ctr_info = NULL;

    // 对传递过来的参数进行解析
    if (NULL != arg)
    {
        ctr_info = (ctr_info_t *)arg;
    }

    if (NULL != ctr_info)
    {
        mqd = ctr_info->mqd;
    }

    while (1)
    {
        printf("%s|%s|%d\n", __FILE__, __func__, __LINE__);
        // 不断读取引脚电平状态
        status = digitalRead(SOMKE_PIN);
        if (LOW == status)
        {
            switch_status = 1; // 表示发送烟雾报警
            // 发送烟雾报警信息
            buffer[2] = 0x45;
            buffer[3] = 0x00;
            printf("%s|%s|%d:0x%x,0x%x,0x%x,0x%x,0x%x,0x%x\n", __FILE__, __func__, __LINE__, buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5]);

            msg_queue_send(mqd, buffer, sizeof(buffer));
        }
        else if (status == HIGH && switch_status == 1)
        {
            switch_status = 0; // 警报解除
            buffer[2] = 0x45;
            buffer[3] = 0x01;
            printf("%s|%s|%d:0x%x,0x%x,0x%x,0x%x,0x%x,0x%x\n", __FILE__, __func__, __LINE__, buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5]);

            msg_queue_send(mqd, buffer, sizeof(buffer));
        }

        sleep(2);
    }

    pthread_exit(NULL);
}

struct control somke_control =
    {
        .control_name = "smoke",
        .init = somke_init,
        .final = somke_final,
        .get = somke_get,
        .set = NULL,
        .next = NULL};

// smoke监听加入链表
struct control *add_somke_to_control(struct control *phead)
{
    return add_interface_to_control_list(phead, &somke_control);
}